from django.http import HttpResponse, HttpResponseNotFound, HttpResponseServerError, HttpResponseRedirect
def index_view(request):
    # 响应，创建响应对象
    html = '<h1>这是首页</h1>'
    return HttpResponse(html)

def test_request(request):
    # request 请求对象
    print('请求方法：', request.method)  # GET/POST
    print('请求路径：', request.path_info)
    print('完整路径：', request.get_full_path())
    # <QueryDict: {'a': ['1'], 'b': ['2']}>
    print('获取GET请求参数：', request.GET)
    # 获取具体的值
    # print('a：', request.GET['a'], )
    # 不存在会是None
    print('a：', request.GET.get('a'))
    # 获取多个
    print('c：', request.GET.getlist('c'))
    return HttpResponse('test request ok!')

def page_view(request):
    # 获取GET传递的参数
    param = request.GET   # {'pno': xx, 'size': xx}
    return HttpResponse(f'当前页码：{param["pno"]}  每页大小：{param["size"]}')

html = '''
    <h2>用户登录</h2>
    <form id="loginForm" action="/login" method="POST">
        <label for="username">用户：</label>
        <input type="text" id="username" name="username" required><br><br>
        <label for="password">密码：</label>
        <input type="password" id="password" name="password" required><br><br>
        <button type="submit">登录</button>
    </form>
'''
def login_view(request):
    # 如果请求方法为GET
    if request.method == 'GET':
        # 响应一段html
        return HttpResponse(html)
    # 如果请求方法为POST
    elif request.method == 'POST':
        # 获取POST传递参数
        param = request.POST
        # <QueryDict: {'username': ['admin'], 'password': ['123456']}>
        print(param)
        return HttpResponse(f'登录成功！欢迎：{param["username"]}')
def test_response(request):
    # 设置响应体
    # 200
    # return HttpResponse('test response!')
    # 设置404
    # return HttpResponseNotFound('客户端错误')
    # 500
    # return HttpResponseServerError('服务器端错误')
    # 302
    return HttpResponseRedirect('/login')
# 导入响应模板函数
from django.shortcuts import render
def test_html(request):
    # 准备一个字典格式数据，然后给模板层
    person = {
        'name': '小明',
        'age': 18,
        'gender': '男'
    }
    # 响应一个模板文件
    return render(request, 'test_html.html', person)
def say_hi():
    return 'hello'
class Person:
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name
    def get_name(self):
        return f'{self.first_name}.{self.last_name}'

def test_html_param(request):
    # 参数类型
    context = {
        'name': '小红',
        'age': 18,
        'is_student': True,
        'hobbies': ['运动', '游戏', '旅游'],
        'book': {'title': 'Python开发', 'price': 49.99},
        'func': say_hi,
        'person': Person('唐纳德', '特朗普')
    }
    return render(request, 'test_html_param.html', context)

def test_if_for(request):
    wendu = 16
    date = '2025-2-8'
    city = ['北京', '上海', '深圳', '广州', '杭州']
    # 将数据渲染到页面中，以表格的形式展示出来
    students = [
        {'id': 1, 'name': '小明', 'gender': '男', 'score': 89},
        {'id': 2, 'name': '小红', 'gender': '女', 'score': 96},
        {'id': 3, 'name': '小丽', 'gender': '女', 'score': 78},
        {'id': 4, 'name': '小东', 'gender': '男', 'score': 85},
    ]
    # 自动将当前函数中的变量放入到字典
    # print(locals())  # {'wendu': wendu, 'date': date}
    return render(request, 'test_if_for.html', locals())

def calc(request):
    title = 'hello WORLD'
    # 如果是GET请求
    if request.method == 'GET':
        return render(request, 'calc.html', locals())
    # 如果是POST请求
    elif request.method == 'POST':
        print(request.POST)
        # 获取传递的参数
        num1 = int(request.POST['num1'])
        num2 = int(request.POST['num2'])
        op = request.POST['op']
        if op == '+':
            result = num1 + num2
        elif op == '-':
            result = num1 - num2
        elif op == '*':
            result = num1 * num2
        else:
            result = num1 / num2
        # 最后还是返回模板页面，只是需要把计算结果传递进去
        return render(request, 'calc.html', locals())